<?php

namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 会员模型
 * @method static mixed getByUsername($str) 通过用户名查询用户
 * @method static mixed getByNickname($str) 通过昵称查询用户
 * @method static mixed getByMobile($str) 通过手机查询用户
 * @method static mixed getByEmail($str) 通过邮箱查询用户
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        //'url',
        'service_status_text'
    ];

    public function getServiceStatusList()
    {
        return [0 => '空闲', 1 => '预约占用',2=>'其他占用',3=>'待上钟',4=>'服务中',5=>'超时'];
    }

    public function getServiceStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['service_status'];
        $list = $this->getServiceStatusList();
        return $list[$value] ?? '';
    }

    public function edit($user_id,$service_status)
    {
        //服务状态,0空闲,1预约占用,2其他占用,3待上钟,4服务中,5超时
        $user = User::get($user_id);
        $user->service_status = $service_status;

        $res = $user->save();
        return $res;
    }



    //上钟修改员工的状态和下钟时间
    public function editServiceStatus($order_id,$user_id)
    {
        $info = Order::get($order_id);

        $user = User::get($user_id);

        $project = StoreProject::get($info['project_id']);

        $minute = $project['hour']*60+$project['minute'];

        $total_minute = bcmul($minute,$info['num'],2);

        $date_timestamp = strtotime($info['date']);

        $work_end_time = bcadd($date_timestamp,$total_minute);

        $info->work_end_time = $work_end_time;

        $info->save();

        $user->work_end_time = $work_end_time;

        $user->service_status = 4;

        $res = $user->save();

        return $res;
    }

    //加钟修改员工的下钟时间
    public function editWorkEndTime($order_id,$project_id,$num,$user_id)
    {
        $info = Order::get($order_id);

        $user = User::get($user_id);

        $project = StoreProject::get($project_id);

        $minute = $project['hour']*60+$project['minute'];

        $total_minute = bcmul($minute,$num,2);

        $date_timestamp = $info->work_end_time;

        $work_end_time = bcadd($date_timestamp,$total_minute);

        $info->work_end_time = $work_end_time;

        $info->save();

        $user->work_end_time = $work_end_time;

        $res = $user->save();

        return $res;
    }


    //计算员工账单
    public function bill($start_date,$end_date,$self,$user_id)
    {
        if ($user_id){
            $search_staff_id = $user_id;
        } else {
            $search_staff_id = $self;
        }

        if (!$start_date&&!$end_date){
            $start_date_timestamp = strtotime('today');
            $end_date_timestamp = strtotime('tomorrow') -1;
        } else {
            $start_date_timestamp = strtotime($start_date);
            $end_date_timestamp = strtotime($end_date);
        }


        $stat_model = new Stat();

        //钟数
        $num = $stat_model->projectNum($search_staff_id,$start_date_timestamp,$end_date_timestamp);

        //刷卡
        $swiping_card_price = $stat_model->swipingCardPrice($search_staff_id,$start_date_timestamp,$end_date_timestamp);

        //刷卡小费
        $swiping_card_tip_price = $stat_model->swipingCardTipPrice($search_staff_id,$start_date_timestamp,$end_date_timestamp);

        //现金
        $cash_price = $stat_model->cashPrice($search_staff_id,$start_date_timestamp,$end_date_timestamp);

        //礼品卡
        $gift_card_price = $stat_model->giftCardPrice($search_staff_id,$start_date_timestamp,$end_date_timestamp);

        //礼品卡小费
        $gift_card_tip_price = $stat_model->giftCardTipPrice($search_staff_id,$start_date_timestamp,$end_date_timestamp);

        //实际营业额（大费）=刷卡+礼品卡+现金
        $turnover = $swiping_card_price+$gift_card_price+$cash_price;

        //每日支票=（刷卡+礼卡+现金+小费）÷2
        $all_income = $swiping_card_price+$gift_card_price+$cash_price+$swiping_card_tip_price+$gift_card_tip_price;
        $cheque = bcdiv($all_income,2,2);

        //每日差价（技师收益）：（刷卡+礼品卡+现金）/2-（刷卡+礼卡+刷卡小费+礼品卡小费）
        $normal_income = bcdiv($turnover,2,2);//（刷卡+礼品卡+现金）/2
        $swiping_gift_income  = $swiping_card_price+$swiping_card_tip_price+$gift_card_price+$gift_card_tip_price;//（刷卡+礼卡+刷卡小费+礼品卡小费）
        $price_spread = bcsub($normal_income,$swiping_gift_income,2);

        $data = [
            'num'=>$num,//钟数
            'swiping_card_price'=>$swiping_card_price,//刷卡
            'swiping_card_tip_price'=>$swiping_card_tip_price,//刷卡小费
            'cash_price'=>$cash_price,//现金
            'gift_card_price'=>$gift_card_price, //礼品卡
            'gift_card_tip_price'=>$gift_card_tip_price,//礼品卡小费
            'cheque'=>$cheque,//每日支票
            'price_spread'=>$price_spread,//每日差价
            'turnover'=>$turnover//营业额
        ];

        return $data;
    }


    //计算门店员工账单
    public function storebill($start_date,$end_date,$store_id,$staff_id)
    {

        if (!$start_date&&!$end_date){
            $start_date_timestamp = strtotime('today');
            $end_date_timestamp = strtotime('tomorrow') -1;
        } else {
            $start_date_timestamp = strtotime($start_date);
            $end_date_timestamp = strtotime($end_date);
        }


        $stat_model = new Stat();

        //钟数
        $num = $stat_model->projectNum($staff_id,$start_date_timestamp,$end_date_timestamp,$store_id);

        //刷卡
        $swiping_card_price = $stat_model->swipingCardPrice($staff_id,$start_date_timestamp,$end_date_timestamp,$store_id);

        //刷卡小费
        $swiping_card_tip_price = $stat_model->swipingCardTipPrice($staff_id,$start_date_timestamp,$end_date_timestamp,$store_id);

        //现金
        $cash_price = $stat_model->cashPrice($staff_id,$start_date_timestamp,$end_date_timestamp,$store_id);

        //礼品卡
        $gift_card_price = $stat_model->giftCardPrice($staff_id,$start_date_timestamp,$end_date_timestamp,$store_id);

        //礼品卡小费
        $gift_card_tip_price = $stat_model->giftCardTipPrice($staff_id,$start_date_timestamp,$end_date_timestamp,$store_id);

        //实际营业额（大费）=刷卡+礼品卡+现金
        $turnover = $swiping_card_price+$gift_card_price+$cash_price;

        //每日支票=（刷卡+礼卡+现金+小费）÷2
        $all_income = $swiping_card_price+$gift_card_price+$cash_price+$swiping_card_tip_price+$gift_card_tip_price;
        $cheque = bcdiv($all_income,2,2);

        //每日差价（技师收益）：（刷卡+礼品卡+现金）/2-（刷卡+礼卡+刷卡小费+礼品卡小费）
        $normal_income = bcdiv($turnover,2,2);//（刷卡+礼品卡+现金）/2
        $swiping_gift_income  = $swiping_card_price+$swiping_card_tip_price+$gift_card_price+$gift_card_tip_price;//（刷卡+礼卡+刷卡小费+礼品卡小费）
        $price_spread = bcsub($normal_income,$swiping_gift_income,2);

        $data = [
            'num'=>$num,//钟数
            'swiping_card_price'=>$swiping_card_price,//刷卡
            'swiping_card_tip_price'=>$swiping_card_tip_price,//刷卡小费
            'cash_price'=>$cash_price,//现金
            'gift_card_price'=>$gift_card_price, //礼品卡
            'gift_card_tip_price'=>$gift_card_tip_price,//礼品卡小费
            'cheque'=>$cheque,//每日支票
            'price_spread'=>$price_spread,//每日差价
            'turnover'=>$turnover//营业额
        ];

        return $data;
    }

    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }
}
